$(function () {
    $("#jqGrid").Grid({
        url: '../modulesppurchasingbatch/list',
        shrinkToFit:false,
        autoScroll: true, //开启水平滚动条
        colModel: [
            {label: '备件名称', name: 'moldSpName', width: 180, index: 'MOLD_SP_ID'},
            {label: '图号', name: 'mapNo', index: 'MOLD_SP_ID', width: 220},
            {label: '供应厂家', name: 'supplierName', width: 150, index: 'SUPPLIER_ID'},
            {label: '单价', name: 'unitPrice', width: 90, index: 'UNIT_PRICE'},
            {label: '开始月份', name: 'beginMonth', width: 90, index: 'BEGIN_MONTH'},
            {label: '截止月份', name: 'endMonth', width: 90, index: 'END_MONTH'},
            {label: '解析规则', name: 'barCordAnalysisRule', index: 'BAR_CORD_ANALYSIS_RULE', width: 300},
            {
                label: '创建时间', name: 'gmtCreate', width: 160, index: 'GMT_CREATE', formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd hh:mm:ss");
                }
            },
            {
                label: '最近一次更新时间', name: 'gmtModified', width: 160, index: 'GMT_MODIFIED', formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd hh:mm:ss");
                }
            },
            {label: '备注', name: 'remark', index: 'REMARK', width: 220},
            {name: 'moldSpId', index: 'MOLD_SP_ID', hidden: true},
            {name: 'supplierId', index: 'SUPPLIER_ID', hidden: true},
            {label: '入库数', name: 'stockInNum', hidden: true},
            {label: '出库数', name: 'stockOutNum', hidden: true},
            {label: 'id', name: 'id', key: true, hidden: true}
        ]
    });
});

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        moduleSpPurchasingBatch: {
            remark: '',
            moldSpId: '',
            moldSpName: '',
            unitPrice: '',
            barCordAnalysisRule: '',
            supplierName: '',
            supplierId: '',
            beginMonth: '', // 开始月份
            endMonth: '', // 结束月份
            id: '',
        },
        ruleValidate: {
            moldSpName: [
                {required: true, message: '型芯必选', trigger: 'change'}
            ],
            supplierName: [
                {required: true, message: '供应厂家必选', trigger: 'change'}
            ],
            unitPrice: [
                {required: true, message: '单价不能为空', trigger: 'blue'}
            ],
            beginMonth: [
                {required: true, message: '单价不能为空', trigger: 'blue'}
            ],
            endMonth: [
                {required: true, message: '单价不能为空', trigger: 'blue'}
            ]
        },
        q: {
            sparePartsName: '',
            mapNo: '',
            supplier: '',
            uniqueBarCode: ''
        }
    },
    methods: {
        // 字符串转日期
        getDate(strDate) {
            let monthStr = strDate.split("-")[1];
            let newMonthStr =  parseInt(monthStr)+"";
            strDate = strDate.split("-")[0]+"-"+ newMonthStr +"-1";
            var date = eval(
                "new Date(" +
                strDate
                    .replace(/\d+(?=-[^-]+$)/, function(a) {
                        return parseInt(a, 10) - 1;
                    })
                    .match(/\d+/g) +
                ")"
            );
            return date;
        },
        // 获取开始月份
        handleChangeBeginMonth(month) {
            this.moduleSpPurchasingBatch.beginMonth = month;
        },
        // 获取结束月份
        handleChangeEndMonth(month) {
            this.moduleSpPurchasingBatch.endMonth = month;
        },
        // 限制可选的开始年月
        startMonthOptions: {
            disabledDate: date => {
                if (this.moduleSpPurchasingBatch.endMonth) {
                    let endDate = this.getDate(this.moduleSpPurchasingBatch.endMonth);
                    return (date && date > endDate) || date > new Date();
                } else {
                    return date && date > new Date();
                }
            }
        },
        // 限制可选的结束年月
        endMonthOptions: {
            disabledDate: date => {
                if (this.moduleSpPurchasingBatch.beginMonth) {
                    let beginDate = this.getDate(this.moduleSpPurchasingBatch.beginMonth);
                    return (date && date < beginDate) || date > new Date();
                } else {
                    return date && date > new Date();
                }
            }
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.moduleSpPurchasingBatch = {
                remark: '',
                moldSpId: '',
                moldSpName: '',
                unitPrice: '',
                barCordAnalysisRule: '',
                supplierName: '',
                supplierId: '',
                beginMonth: '', // 开始月份
                endMonth: '', // 结束月份
                id: '',
            };
            this.$nextTick(() => this.$refs.moldSpNameInput.focus());
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            let url = vm.moduleSpPurchasingBatch.id == (null || '') ? "../modulesppurchasingbatch/save" : "../modulesppurchasingbatch/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.moduleSpPurchasingBatch),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../modulesppurchasingbatch/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        // 选择厂家
        loadFacType: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择厂家',
                content: '../sys/factorytype_choose.html?type=2',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getFacType();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.moduleSpPurchasingBatch.supplierName = res.faName;
                        vm.moduleSpPurchasingBatch.supplierId = res.id;
                    }
                }
            })
        },
        // 选择型芯
        getSpareInfo: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择备件',
                content: '../module/moldSpSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getSparePart();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.moduleSpPurchasingBatch.moldSpId = res.id;
                        vm.moduleSpPurchasingBatch.moldSpName = res.name;
                        vm.moduleSpPurchasingBatch.mapNo = res.mapNo;
                        layer.close(index);
                    }
                }
            })
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../modulesppurchasingbatch/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.moduleSpPurchasingBatch = r.moduleSpPurchasingBatch;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'sparePartsName': vm.q.sparePartsName,'mapNo': vm.q.mapNo,'supplier': vm.q.supplier,'uniqueBarCode': vm.q.uniqueBarCode},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                sparePartsName: '',
                mapNo: '',
                supplier: '',
                uniqueBarCode: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                iview.Message.success('文件上传成功');
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        }
    }
});
